package com.miaopasi.learn.springcloud.alibaba.seata.service.impl;

import cn.hutool.log.StaticLog;
import com.miaopasi.learn.springcloud.alibaba.seata.mapper.OrderMapper;
import com.miaopasi.learn.springcloud.alibaba.seata.model.Order;
import com.miaopasi.learn.springcloud.alibaba.seata.service.AccountService;
import com.miaopasi.learn.springcloud.alibaba.seata.service.OrderService;
import com.miaopasi.learn.springcloud.alibaba.seata.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单service实现类
 *
 * @author lixin
 */
@Service
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final StorageService storageService;
    private final AccountService accountService;

    @Autowired
    public OrderServiceImpl(OrderMapper orderMapper, StorageService storageService, AccountService accountService) {
        this.orderMapper = orderMapper;
        this.storageService = storageService;
        this.accountService = accountService;
    }

    @Override
    @GlobalTransactional(name = "seata_order_transation", rollbackFor = Exception.class)
    public void create(Order order) {
        StaticLog.info("---1、开始创建订单---");
        orderMapper.create(order);

        StaticLog.info("---2、调用库存，扣减库存---");
        storageService.decrease(order.getProductId(), order.getCount());

        StaticLog.info("---3、调用账户，扣减余额---");
        accountService.decrease(order.getUserId(), order.getMoney());

        StaticLog.info("---4、修改订单状态---");
        orderMapper.updateStatus(order.getId(), 1);

        StaticLog.info("---5、创建订单结束---");
    }

}
